<template>
	<view v-if="isLogin">
		<view class="header">
			<view class="total-count">共{{ cartList.length }}件商品</view>
			<view style="display: flex; gap: 10rpx">
				<view class="operation-btn" @click="deleteFlag = !deleteFlag">
					{{ deleteFlag ? "完成" : "编辑" }}
				</view>
				<view class="operation-btn" @click="exportExcel"> 导出excel </view>
			</view>
		</view>
		<uni-list :border="true">
			<uni-list-item v-for="item in cartList" :key="item.id" :title="item.goods_name"
				:note="specFn(item.spec_info)">
				<template v-slot:header>
					<view class="slot-box">
						<radio :checked="item?.checked" @click="handleCheck(item)" />
						<view class="headerSlot" :style="{ backgroundImage: `url(${item.goods_big_img})` }"></view>
					</view>
				</template>
				<template v-slot:body>
					<view class="goods-info">
						<view class="goods-name">{{ item.goods_desc }}</view>

						<view class="goods-price">￥<text class="price">{{ item.price }}</text></view>
					</view>
				</template>
				<template v-slot:footer>
					<view class="goods-action">
						<uni-number-box min="1" v-if="!deleteFlag" v-model="item.num"
							@change="handleNumChange(item)"></uni-number-box>
						<view class="delete-btn" v-else @click="delGoods(item)">删除</view>
					</view>
				</template>
			</uni-list-item>
		</uni-list>
		<view style="height: 100rpx;"></view>
		<view class="cart-footer">
			<view class="select-all">
				<radio class="inputRadio" :checked="allCheck" @click="handleAllCheck" />
				<text @click="handleAllCheck">全选</text>
			</view>
			<view class="total-price">
				<text>合计：</text>
				<text class="price">￥{{ totalPrice }}</text>
			</view>
			<view class="submit-btn" @click="submitFn">提交订单</view>
		</view>
	</view>
	<view v-else class="login-container">
		<button class="login-btn" @click="doLogin">请先登录</button>
	</view>
	<!-- 普通弹窗 -->
	<uni-popup ref="popupBottom" background-color="#fff" @change="change">
		<view class="popup-content" :style="{height:isIOS()?'290rpx':'350rpx'}">
			<view style="padding: 20rpx 0">导出excel清单</view>
			<view style="display: flex; gap: 40rpx; padding: 0 20rpx">
				<view style="display: flex; flex: 1; align-items: center">
					<view style="">本体折扣：</view>
					<view style="flex: 1">
						<input class="uni-input" v-model="sendEmailOption.goods_discount" />
					</view>
					<view>%</view>
				</view>
				<view style="display: flex; align-items: center; flex: 1; padding: 0 20rpx">
					<view style="">附件折扣：</view>
					<view style="flex: 1">
						<input class="uni-input" v-model="sendEmailOption.atta_discount" />
					</view>
					<view>%</view>
				</view>
			</view>
			<view style="display: flex; width: 90%; padding: 0 20rpx">
				<view style="width: 100rpx">邮箱：</view>
				<view style="flex: 1"><input class="uni-input" v-model="sendEmailOption.email" /></view>
			</view>
			<view style="font-size: 24rpx; color: #666">我们需要将excel发送至您的邮箱，请您去邮箱中下载</view>
			<view style="display: flex; width: 100%">
				<view style="flex: 1" class="cancel-btn" @click="popupBottom.close()">取消</view>
				<view style="flex: 1" class="send-btn" @click="sendEmail">发送</view>
			</view>
		</view>
	</uni-popup>

</template>

<script setup>
	import {
		ref,
		computed,
		reactive
	} from "vue";
	import {
		onShow
	} from "@dcloudio/uni-app";
	import {
		getCartsList,
		cartsChecked,
		cartsAllChecked,
		cartsNumAdd,
		cartsDelAll,
		submitOrder,
		sendCarts,
	} from "@/api/index.js";
	const popupBottom = ref(null);
	import {
		getUser
	} from "../../utils/token";
	const sendEmailOption = reactive({
		customer_id: "",
		goods_discount: "",
		atta_discount: "",
		email: "",
	});
	function isIOS() {
		console.log(uni.getSystemInfoSync().platform === 'ios')
      return uni.getSystemInfoSync().platform === 'ios'
    }
	function sendEmail() {
		if (!sendEmailOption.email) {
			uni.showToast({
				title: "请输入邮箱",
				icon: "none",
			});
			return;
		} else if (!sendEmailOption.goods_discount) {
			uni.showToast({
				title: "请输入本体折扣",
				icon: "none",
			});
			return;
		} else if (!sendEmailOption.atta_discount) {
			uni.showToast({
				title: "请输入附件折扣",
				icon: "none",
			});
			return;
		} else {
			sendCarts(sendEmailOption).then((res) => {
				if (res.code == 0) {
					uni.showToast({
						title: `邮件发送成功，请稍后到邮箱(${sendEmailOption.email})下载`,
						icon: "success",
					});
					popupBottom.value.close();
				} else {
					uni.showToast({
						title: res.msg,
						icon: "none",
					});
				}
			});
		}
	}
	const isLogin = ref(false);
	const cartList = ref([]);
	const allCheck = ref(false);
	const deleteFlag = ref(false);
	let user;

	// 计算总价
	const totalPrice = computed(() => {
		let total = 0;
		cartList.value.forEach((item) => {
			if (item.checked) {
				total += item.price * item.num;
			}
		});
		return total === 0 ? "价格面议" : total.toFixed(2);
	});

	// 全选处理
	function handleAllCheck() {
		allCheck.value = !allCheck.value;
		cartList.value.forEach((item) => {
			item.checked = allCheck.value;
		});
		if (allCheck.value) {
			cartsAllChecked(user.id, 1);
		}
	}

	function exportExcel() {
		popupBottom.value.open("bottom");
	}
	// 单个商品选中处理
	function handleCheck(item) {
		item.checked = !item.checked;
		if (item.id) {
			cartsChecked(item.id, item.checked ? 1 : 0);
		}
		// 更新全选状态
		allCheck.value = cartList.value.every((item) => item.checked);
	}

	// 数量变化处理
	function handleNumChange(item) {
		cartsNumAdd(item.id, item.num);
		// 重新计算价格
	}

	// 删除商品
	function delGoods(item) {
		uni.showModal({
			title: "提示",
			content: "确定要删除该商品吗？",
			success: (res) => {
				if (res.confirm) {
					cartsDelAll(item.id).then(() => {
						getList();
					});
				}
			},
		});
	}

	// 获取购物车列表
	function getList() {
		getCartsList(user.id).then((res) => {
			cartList.value = res.data;
			// 初始化选中状态
			allCheck.value = cartList.value.every((item) => item.checked);
		});
	}

	// 规格格式化
	function specFn(arr) {
		if (!arr || !arr.length) return "";
		return "规格：" + arr.map((item) => item.value_name).join(" ");
	}

	// 登录跳转
	function doLogin() {
		uni.navigateTo({
			url: "/wuLian/pages/login",
		});
	}

	// 提交订单
	function submitFn() {
		if (!user.id) return;

		const selectedItems = cartList.value.filter((item) => item.checked);
		if (selectedItems.length === 0) {
			uni.showToast({
				title: "请选择要购买的商品",
				icon: "none",
			});
			return;
		}

		uni.showLoading({
			title: "加载中..."
		});
		submitOrder(user.id).then(() => {
			uni.hideLoading();
			uni.redirectTo({
				url: "/mine/pages/callMsg",
			});
		});
	}

	onShow(() => {
		user = getUser();
		if (user) {
			isLogin.value = true;
			sendEmailOption.customer_id = user.id;
			getList();
		}
	});
</script>

<style scoped>
	.btnContact {
		display: none;
	}

	.cancel-btn {
		background-color: #333;
		color: #fff;
		height: 80rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.popup-content {
		display: flex;
		flex-direction: column;
		gap: 20rpx;
		text-align: center;
		justify-content: space-between;
		align-items: center;
		font-size: 26rpx;
		height: 350rpx;
	}

	/* 判断 iOS 设备 */
	@media only screen and (max-device-width: 480px) and (-webkit-min-device-pixel-ratio: 2) {
		.popup-content {
			height: 290rpx;
		}
	}

	/* 针对 iOS 设备的特定样式 */

	.ios .popup-content {
		height: 290rpx;
	}


	/* 针对非 iOS 设备（通常是 Android） */

	.android .popup-content {
		height: 350rpx;
	}


	.uni-input {
		border: 1rpx solid #ccc;
	}

	.send-btn {
		background-color: #e60012;
		color: #fff;
		height: 80rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.header {
		padding: 20rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.total-count {
		font-size: 28rpx;
		color: #333;
	}

	.operation-btn {
		font-size: 24rpx;
		background-color: #e60012;
		padding: 10rpx 20rpx;
		color: #fff;
		border-radius: 10rpx;
	}

	.slot-box {
		display: flex;
		align-items: center;
		gap: 20rpx;
		width: 180rpx;
	}

	.headerSlot {
		width: 150rpx;
		height: 150rpx;
		background-position: center;
		background-repeat: no-repeat;
		background-size: contain;
		border-radius: 8rpx;
	}

	.goods-info {
		flex: 1;
		font-size: 26rpx;
		padding: 0 20rpx;
		min-width: 0;
		/* 确保flex布局下文本可以正确省略 */
	}

	.goods-name {
		font-weight: bold;
		margin-bottom: 10rpx;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
		width: 100%;
	}

	.goods-spec {
		color: #666;
		margin-bottom: 10rpx;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
		width: 100%;
	}

	.goods-price {
		color: #333;
		margin-top: 10rpx;
	}

	.price {
		color: #e60012;
		font-size: 32rpx;
	}

	.goods-action {
		padding-top: 30rpx;
		min-width: 160rpx;
		text-align: right;
	}

	.delete-btn {
		background-color: #e60012;
		color: #fff;
		padding: 10rpx 20rpx;
		font-size: 24rpx;
		border-radius: 10rpx;
		text-align: center;
	}

	.cart-footer {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 100rpx;
		display: flex;
		align-items: center;
		background-color: #fff;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	.select-all {
		flex: 1;
		padding-left: 30rpx;
		display: flex;
		align-items: center;
		gap: 10rpx;
	}

	.total-price {
		flex: 2;
		padding-left: 20rpx;
	}

	.submit-btn {
		flex: 1;
		background-color: #e60012;
		color: #fff;
		height: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 28rpx;
	}

	.login-container {
		width: 100%;
		height: 100vh;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.login-btn {
		width: 50%;
		background-color: #e60012;
		color: #fff;
	}

	/* 调整列表项布局 */
	:deep(.uni-list-item) {
		padding: 20rpx 0;
	}

	:deep(.uni-list-item__container) {
		padding: 0 20rpx;
	}

	:deep(.uni-list-item__content-title) {
		display: none;
		/* 隐藏默认的标题，使用自定义布局 */
	}

	:deep(.uni-list-item__content-note) {
		display: none;
		/* 隐藏默认的备注，使用自定义布局 */
	}
</style>